package com.example.foo.api.web.product;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.ruoyi.common.core.domain.AjaxResult;
import com.example.foo.product.model.Bag;
import com.example.foo.product.model.Item;
import com.example.foo.product.service.BagService;
import com.example.foo.product.service.ItemService;

@org.springframework.web.bind.annotation.RestController
public class BagItemAction {

	private final BagService bagService;
	private final ItemService itemService;

	public BagItemAction(BagService bagService, ItemService itemService) {
		this.bagService = bagService;
		this.itemService = itemService;
	}

	@GetMapping("/api/bagitems/bagId={bagId}")
	public AjaxResult showBagItem(@PathVariable("bagId") Long bagId) {
		Bag bag = bagService.findBagById(bagId);
		if (bag == null) {
			return AjaxResult.error(404, "Not Found");
		}
		if (bag.getState() != Bag.State.published) {
			return AjaxResult.error(404, "Not Found");
		}

		List<Long> giftItemIds = Arrays.stream(bag.getGiftItemIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
		List<Item> giftItems = itemService.findItemsByIds(giftItemIds);
		giftItems = giftItems.stream()
				.filter(t -> t.getState() == Item.State.published)
				.sorted((o1, o2) -> giftItemIds.indexOf(o1.getId()) - giftItemIds.indexOf(o2.getId()))
				.collect(Collectors.toList());

		return AjaxResult.successData(new BagItemVO(bag, giftItems));
	}

}
